package cn.sll.search.service.impl;

import cn.sll.base.util.*;
import cn.sll.org.domain.Shop;
import cn.sll.org.mapper.ShopMapper;
import cn.sll.search.domain.SearchMasterMsg;
import cn.sll.search.domain.SearchMasterMsgAuditLog;
import cn.sll.search.dto.SearchMasterMsgDto;
import cn.sll.search.mapper.SearchMasterMsgAuditLogMapper;
import cn.sll.search.service.ISearchMasterMsgService;
import cn.sll.base.service.impl.BaseServiceImpl;
import cn.sll.user.domain.User;
import cn.sll.user.mapper.LogininfoMapper;
import cn.sll.user.mapper.UserMapper;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author sll
 * @since 2023-01-10
 */
@Service
public class SearchMasterMsgServiceImpl extends BaseServiceImpl<SearchMasterMsg> implements ISearchMasterMsgService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private SearchMasterMsgAuditLogMapper searchMasterMsgAuditLogMapper;

    @Autowired
    private ShopMapper shopMapper;

    @Override
    public AjaxResult publish(SearchMasterMsgDto dto) {
        // 校验数据

        // 1.保存数据
        SearchMasterMsg searchMasterMsg = new SearchMasterMsg();
        BeanUtils.copyProperties(dto,searchMasterMsg);
        // 设置状态 0:待审核 1:审核通过 2:审核失败 3:已接单 4:已完成
        searchMasterMsg.setState(0);
        // 设置userId 当心 空指针
        Long LogininfoId = LoginContext.getUserInfo().getLogininfo().getId();
        // 通过logininfo的id查询userid
        User user = userMapper.findByIdLogininfo(LogininfoId);
        searchMasterMsg.setUserId(user.getId());
        super.add(searchMasterMsg);

        // 2.百度AI审核
        if(!BaiduAuditUtils.TextCensor(searchMasterMsg.getName())){
            // 改状态
            searchMasterMsg.setState(2);
            // 审核不通过 添加日志
            SearchMasterMsgAuditLog searchMasterMsgAuditLog = new SearchMasterMsgAuditLog();
            searchMasterMsgAuditLog.setMsgId(searchMasterMsg.getId());
            searchMasterMsgAuditLog.setState(0);
            searchMasterMsgAuditLog.setAuditId(-1L);
            searchMasterMsgAuditLog.setAuditTime(new Date());
            searchMasterMsgAuditLog.setNote("宠物名字审核不通过"+searchMasterMsg.getName());
            searchMasterMsgAuditLogMapper.add(searchMasterMsgAuditLog);
        }else{
            // 审核通过 改状态
            searchMasterMsg.setState(1);
            // 3.找店铺
            Point point = DistanceUtil.getPoint(searchMasterMsg.getAddress());
            List<Shop> shopList = shopMapper.findAll();
            Shop nearestShop = DistanceUtil.getNearestShop(point, shopList);
            if (null != nearestShop){
            searchMasterMsg.setShopId(nearestShop.getId());
            }
        }
        // 4.最后 更新状态
        super.update(searchMasterMsg);
        return AjaxResult.me().success();
    }
}
